package com.rpp.client;

import com.rpp.config.ZookeeperConfig;
import com.rpp.handler.UserClientHandler;
import com.rpp.request.RpcRequest;
import com.rpp.serialize.JSONSerializer;
import com.rpp.utils.RpcDecoder;
import com.rpp.utils.RpcEncoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.I0Itec.zkclient.IZkChildListener;
import org.I0Itec.zkclient.ZkClient;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


/**
 * 消费者
 */
public class RPCConsumer_1 implements IZkChildListener {

    private static ZkClient zkClient;

    /**
     * 1.创建一个线程池对象  -- 它要处理我们自定义事件
     */
    private static ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    /**
     * 声明一个自定义事件处理器  UserClientHandler
     */
    private static Map<String, UserClientHandler> handlerMap = new HashMap<>(4);

    /**
     * 连接池对象
     */
    private static Map<String, EventLoopGroup> eventLoopGroupMap = new HashMap<>(4);

    /**
     * 客户端引导对象
     */
    private static Map<String, Bootstrap> bootstrapHashMap = new HashMap<>(4);

    static {
        //初始化客户端cliet
        zkClient = new ZkClient(ZookeeperConfig.connectionString);
        System.out.println("zookeeper会话创建成功..");

        //注册子节点列表变化事件，当子节点即服务节点下线或者上线以后可以获取到通知，然后断开连接或者重新连接
        zkClient.subscribeChildChanges(ZookeeperConfig.SERVER_NODE, new RPCConsumer_1());
    }

    /**
     * 3.编写方法,初始化客户端  ( 创建连接池  bootStrap  设置bootstrap  连接服务器)
     *
     * @throws InterruptedException
     */
    public static void initClient(String connectionUrl, UserClientHandler userClientHandler) throws InterruptedException {

        //2)创建连接池对象
        EventLoopGroup group = eventLoopGroupMap.computeIfAbsent(connectionUrl, v -> new NioEventLoopGroup());

        //3)创建客户端的引导对象
        Bootstrap bootstrap = bootstrapHashMap.computeIfAbsent(connectionUrl, v -> new Bootstrap());

        //4)配置启动引导对象
        bootstrap.group(group)
                //设置通道为NIO
                .channel(NioSocketChannel.class)
                //设置请求协议为TCP
                .option(ChannelOption.TCP_NODELAY, true)
                //监听channel 并初始化
                .handler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        //获取ChannelPipeline
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        //设置编码器
                        pipeline.addLast(new RpcEncoder(RpcRequest.class, new JSONSerializer()));
                        //设置解码器
                        pipeline.addLast(new RpcDecoder(String.class, new JSONSerializer()));
                        //添加自定义事件处理器
                        pipeline.addLast(userClientHandler);
                    }
                });
        System.out.println("客户端启动成功。。。开始建立连接:" + connectionUrl);

        //5)连接服务端
        String[] split = connectionUrl.split(":");
        String ip = split[0];
        Integer port = Integer.parseInt(split[1]);
        bootstrap.connect(ip, port).sync();
        System.out.println(String.format("连接服务端：IP：%s,端口：%s", ip, port));
    }

    /**
     * 4.编写一个方法,使用JDK的动态代理创建对象
     *
     * @param serviceClass 接口类型,根据哪个接口生成子类代理对象;
     * @return
     */
    public static Object createProxy(Class<?> serviceClass) {
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class[]{serviceClass}, new InvocationHandler() {
                    public Object invoke(Object o, Method method, Object[] objects) throws Throwable {

                        Object result = null;
                        List<String> childNode = zkClient.getChildren(ZookeeperConfig.SERVER_NODE);
                        for (String s : childNode) {
                            //初始化UserClientHandler
                            UserClientHandler userClientHandler = handlerMap.get(s);
                            if (null == userClientHandler) {
                                userClientHandler = new UserClientHandler();
                                handlerMap.put(s, userClientHandler);
                                //初始化客户端cliet
                                initClient(s, userClientHandler);
                            }

                            //封装通信协议对象
                            RpcRequest rpcRequest = initRpcRequest(serviceClass, method, objects[0]);
                            userClientHandler.setRpcRequest(rpcRequest);
                            //使用线程池,开启一个线程处理处理call() 写操作,并返回结果
                            result = executorService.submit(userClientHandler).get();
                            System.out.println(s + "服务器返回结果：" + result);
                        }

                        //return 结果
                        return result;
                    }
                });
    }

    /**
     * 封装通信协议对象
     *
     * @param serviceClass
     * @param method
     * @param param
     * @return
     */
    private static RpcRequest initRpcRequest(Class<?> serviceClass, Method method, Object param) {
        RpcRequest rpcRequest = new RpcRequest();
        //class名称
        rpcRequest.setClassName(serviceClass.getSimpleName());
        //方法名称
        rpcRequest.setMethodName(method.getName());
        //参数
        rpcRequest.setParameters(new Object[]{param});
        //参数类型
        rpcRequest.setParameterTypes(new Class[]{param.getClass()});
        return rpcRequest;
    }

    /**
     * parentPath节点的子节点列表发生变化，都会触发此通知
     *
     * @param parentPath
     * @param currentChilds
     * @throws Exception
     */
    @Override
    public void handleChildChange(String parentPath, List<String> currentChilds) throws Exception {

        //与下线的服务端断开连接
        Set<String> nodes = handlerMap.keySet();
        for (String node : nodes) {
            //当前的子节点不包含之前连接的服务地址，断开连接
            if (!currentChilds.contains(node)) {
                eventLoopGroupMap.get(node).shutdownGracefully();
                System.out.println("客户端与：" + node + "断开连接");
                eventLoopGroupMap.remove(node);
                bootstrapHashMap.remove(node);
            }
        }

        //与重新上线的服务端建立连接
        for (String currentChild : currentChilds) {
            if (!eventLoopGroupMap.containsKey(currentChild)) {

                UserClientHandler userClientHandler = new UserClientHandler();
                handlerMap.put(currentChild, userClientHandler);

                //初始化客户端 并创建连接
                initClient(currentChild, userClientHandler);

                System.out.println("客户端与：" + currentChild + "重新连接");
            }
        }
    }
}
